import { lookup } from './lookup'
/**
 * 渲染数据
 * @param {Array} tokens 
 * @param {Object} data 
 * @returns 
 */
export function render(tokens, data) {
    var renderStr = "";
    for (let i = 0; i < tokens.length; i++) {
        const token = tokens[i];
        switch (token[0]) {
            case "text":
                renderStr += token[1];
                break;

            case "name":
                renderStr += lookup(data, token[1]);
                break;

            case "#":
                renderStr += parseArray(token, data);
                break;

            default:
                break;
        }

    }
    return renderStr;
};

/**
 * 遍历组装token数组，调用render，调用次数由data决定
 * @param {Array} token 
 * @param {Object} data 
 * @description ["#","arrs",[]]
 */
export function parseArray(token, data) {
    console.log(token, data);
    var v = lookup(data, token[1]);
    var resultStr = "";
    if (!v) return "";
    for (let i = 0; i < v.length; i++) {
        //解决[1,2,3]类数组问题
        resultStr += render(token[2], {
            ...v[i],
            '.': v[i]
        });
    }
    return resultStr;
};